import { h, computed } from 'vue'
import { cn } from '../../lib/utils'

// 定义类型接口
interface Column {
  prop?: string
  label?: string
  width?: number
  type?: string
  [key: string]: any
}

interface TableStore {
  columns: Column[]
  colWidths: number[]
  contentWidth: number
}

interface Props {
  store: TableStore
}

// 使用setup函数组件方式
const TableHeader = {
  name: 'CGTableHeader',
  props: {
    store: {
      type: Object,
      required: true
    }
  },
  setup(props: Props) {
    // 计算表格宽度
    const tableWidth = computed(() => {
      return props.store?.contentWidth || '100%'
    })

    // 渲染表头单元格
    const renderHeaderCell = (column: Column) => {
      return h(
        'th',
        {
          class: 'cg-table__cell',
          key: column.prop || column.type || Math.random().toString(36).substring(2)
        },
        [
          h('div', { class: 'cell' }, column.label || '')
        ]
      )
    }

    // 渲染列宽定义
    const renderColGroup = () => {
      if (!props.store?.columns || !props.store.columns.length) {
        return null
      }

      return h(
        'colgroup',
        {},
        props.store.columns.map((column: Column, index: number) => {
          const propName = column.prop || column.type || `col-${index}`
          const width = props.store.colWidths[index] || 0
          
          return h(
            'col',
            {
              name: propName,
              key: propName,
              width: Math.max(0, width)
            }
          )
        })
      )
    }

    return () => {
      // 检查是否有列数据
      if (!props.store?.columns || !props.store.columns.length) {
        return null
      }

      const { columns } = props.store

      return h(
        'table',
        {
          class: 'cg-table__head',
          cellspacing: 0,
          cellpadding: 0,
          border: 0,
          style: {
            width: typeof tableWidth.value === 'number' ? `${tableWidth.value}px` : tableWidth.value
          }
        },
        [
          renderColGroup(),
          h(
            'thead',
            {
              class: ['bg-gray-50', 'font-bold']
            },
            [
              h('tr', {}, columns.map(renderHeaderCell))
            ]
          )
        ]
      )
    }
  }
}

export default TableHeader